package online.longzipeng.back.common.config;

import cn.hutool.core.lang.generator.SnowflakeGenerator;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Author: lzp
 * @description:
 * @Date: 2022/5/15
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    SnowflakeGenerator snowflakeGenerator;

    @Override
    public void insertFill(MetaObject metaObject) {
        // 自动注入创建时间和更新时间
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        // 雪花算法自动注入id
        this.strictInsertFill(metaObject, "id", Long.class, snowflakeGenerator.next());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 自动更新修改时间
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }
}
